#include "FoGGEDEF.h"
#include "FileOutTerminal.h"
#include <fstream>

namespace _FOGGE_
{
	namespace _UTIL_
	{

		FileOutTerminal::FileOutTerminal(foString name,foUInt size)
		{
			m_strLogFileName = name;

			m_uiQueueSIze = size;
		}

		FileOutTerminal::~FileOutTerminal(void)
		{
		}
		void FileOutTerminal::Write_Implement( LPCTSTR str )
		{
			m_strCurrentLine += str;
			ProcessCurrentLine();
		}
		void FileOutTerminal::Flush_Implement()
		{

			if(m_strCurrentLine.size()>0)
				m_History.push(m_strCurrentLine);
			std::ofstream ofile;

			ofile.open(m_strLogFileName.c_str());

			bool re=ofile.is_open();

			while(0< m_History.size())
			{
				
				ofile<<m_History.front()<<"\n";

				m_History.pop();
			}

			ofile.close();
		}

		void FileOutTerminal::ProcessCurrentLine()
		{
			foString::size_type result;
			while(result=m_strCurrentLine.find_first_of("\n"),result!=foString::npos)
			{
				
				m_History.push(m_strCurrentLine.substr(0,result));

				m_strCurrentLine=m_strCurrentLine.substr(result+1);

			}

			if(m_uiQueueSIze>0)
			{
				int diff= m_History.size() - m_uiQueueSIze;

				//remove overflowed str
				for(int i=0;i<diff;i++)
				{
					m_History.pop();					
				}
			}
		}
	}
}